package name.xiaokan.mainframe;

import java.util.LinkedList;
import java.util.Properties;

import name.xiaokan.model.Word;

public class TransitionThread extends Thread {

    private float speed;
    private int sleepMillis = 1000;
    private LinkedList<Word> list;
    private int currentPosition = 0;
    private MainFrame frame;
    private Properties prop;
    private boolean flag = true;

    @SuppressWarnings("finally")
    @Override
    public void run() {
	try {
	    currentPosition = Integer.parseInt(prop.getProperty("cur_pos"));
	    System.out.format("%d/%d", currentPosition, list.size());
	} catch (NumberFormatException e1) {
	    e1.printStackTrace();
	} finally {
	    while (true) {
		refresh();
		currentPosition++;
		if (currentPosition >= list.size())
		    currentPosition = 0;
		prop.setProperty("cur_pos", "" + currentPosition);
		try {
		    this.sleep(sleepMillis);
		} catch (InterruptedException e) {
		    e.printStackTrace();
		    this.interrupt();
		}
	    }
	}
    }

    private void refresh() {
	Word word = list.get(currentPosition);
	frame.getWordText().setText(word.getWord());
	frame.getCountLabel().setText(currentPosition + "");
	String[] str = word.getMeaning();
	StringBuffer sb = new StringBuffer();
	for (String s : str) {
	    sb.append(s);
	    sb.append('\n');
	}
	frame.getMeaningText().setText(sb.toString());
    }

    public float getSpeed() {
	return speed;
    }

    public synchronized void setSpeed(float speed) {
	this.speed = speed;
	this.sleepMillis = (int) (speed * 100);
    }

    public LinkedList<Word> getList() {
	return list;
    }

    public synchronized void setList(LinkedList<Word> list) {
	this.list = list;
    }

    public synchronized MainFrame getFrame() {
	return frame;
    }

    public synchronized void setFrame(MainFrame frame) {
	this.frame = frame;
    }

    public int getCurrentPosition() {
	return currentPosition;
    }

    public synchronized void setCurrentPosition(int currentPosition) {
	this.currentPosition = currentPosition;
	refresh();
    }

    public Properties getProp() {
	return prop;
    }

    public void setProp(Properties prop) {
	this.prop = prop;
    }

}
